import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import { Key, useMemo, useState } from 'react'
import type { TableRowSelection } from 'antd/es/table/interface';

/**
 *
 * @param defaultSelectedRowKeys 默认选中项
 * @returns
 */

interface RowSelectionProps {
  defaultSelectedRowKeys?: Key[]
  canDeleteKeys?: Key[]
}

export interface MyRowSelectionType{
  selectedRowKeys: Key[];
  selectedRows: any[];
  setSelectedRowKeys: React.Dispatch<React.SetStateAction<Key[]>>;
  setSelectRows: React.Dispatch<React.SetStateAction<any[]>>;
  onChange: (rowKeys: any, rows: any) => void;
  clearSelected: () => void;
  deleteDisable: boolean;
}

export const useRowSelection = ({ defaultSelectedRowKeys = [], canDeleteKeys = [] }: RowSelectionProps) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState(defaultSelectedRowKeys)
  const [selectedRows, setSelectRows] = useState<any[]>([])

  const onChange = (rowKeys, rows) => {
    setSelectedRowKeys(rowKeys)
    setSelectRows(rows)
  }
  // 确定清除选中项
  const clearSelected = () => {
    setSelectedRowKeys([])
    setSelectRows([])
  }

  const deleteDisable = useMemo(() => {
    if (selectedRows.length === 0) return true
    if (canDeleteKeys.length > 0 && selectedRows.length > 0) {
      // 这个key对应的value 是 true 则不能删除
      let flag = false
      canDeleteKeys.forEach(key => {
        if (!flag) {
          flag = selectedRows.some(row => row[key as string | number])
        }
      })
      return flag
    }
    return false
  }, [selectedRows])

  return {
    selectedRowKeys,
    selectedRows,
    setSelectedRowKeys,
    setSelectRows,
    onChange,
    clearSelected,
    deleteDisable
  }
}
